package com.sunshine.security;

import com.sunshine.bean.User;
import com.sunshine.exception.InvalidJwtTokenException;
import com.sunshine.exception.InvalidUserException;
import com.sunshine.util.Requests;
import io.jsonwebtoken.ExpiredJwtException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static org.springframework.security.core.context.SecurityContextHolder.getContext;


/**
 * Created by along on 4/20/18.
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    static final String TOKEN_HEADER = "Authorization";
    static final String TOKEN_HEAD = "Bearer ";

    private static final Logger LOGGER = LoggerFactory.getLogger(JwtAuthenticationTokenFilter.class);
    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private Requests requests;

    /**
     * Notice:
     * Need optimize
     *
     * @param request  HttpServletRequest
     * @param response HttpServletResponse
     * @param chain    FilterChain
     * @throws ServletException ServletException
     * @throws IOException      IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {
        if (getContext().getAuthentication() == null) {
            try {
                requests.getUser(request)
                        .map(User::getName)
                        .map(userDetailsService::loadUserByUsername) //  username is id
                        .map(detail -> new UsernamePasswordAuthenticationToken(detail, null, detail.getAuthorities()))
                        .map(token -> {
                            token.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                            return token;
                        })
                        .ifPresent(getContext()::setAuthentication);
            } catch (InvalidJwtTokenException e) {
                LOGGER.warn("Invalid jwt token from: {}, exception info {}", request.getRemoteAddr(), e.getMessage());
            } catch (ExpiredJwtException e) {
                LOGGER.error(e.getMessage());
            } catch (UsernameNotFoundException e) {
                LOGGER.error(e.getMessage());
            } catch (InvalidUserException e) {
                LOGGER.error(e.getMessage());
            }
        }

        chain.doFilter(request, response);
    }
}
